package com.learn.security.handler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;

import com.alibaba.fastjson2.JSON;
import com.learn.result.ResultUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler{

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        //        
        response.setContentType("application/json;charset=UTF-8");
        String message = "";
        int code = 700; // 默认错误码
        if(exception instanceof AccountExpiredException){
            message = "账号已过期，请联系管理员";
        }else if(exception instanceof BadCredentialsException){
            message = "用户名或密码错误";
        }else if(exception instanceof CredentialsExpiredException){
            message = "密码已过期，请联系管理员";
        }else if (exception instanceof DisabledException){
            message = "账号已被禁用，请联系管理员";
        }else if(exception instanceof LockedException){
            message = "账号已被锁定，请联系管理员";
        }else if(exception instanceof InternalAuthenticationServiceException){
            message = "内部认证服务异常，请联系管理员";
        }else{
            message = "认证失败，请重试";
        }
        ServletOutputStream outputStream = response.getOutputStream();
        String result = JSON.toJSONString(ResultUtils.error(code,message));
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
    
}
